const connection = require("../app/database");
class MomentService {
  // 新增内容
  async create(content, userId) {
    const statement = `INSERT INTO moment (content,user_id) VALUES (?,?)`;
    const [result] = await connection.execute(statement, [content, userId]);
    return result;
  }

  // 分页查询内容
  async queryList(offset=0,size=10)
  {
    const statement=`
    SELECT m.id id, m.user_id userId,m.content content,m.createAt createTime, m.updateAt updateTime,
    JSON_OBJECT('id', u.id, 'name', u.name, 'createTime', u.createAt, 'updateTime', u.updateAt) user
    FROM moment m LEFT JOIN user u ON m.user_id=u.id
    LIMIT ? OFFSET ?
    `
    const  [result] =await connection.execute(statement,[String(size),String(offset)])
    return result
  }
  // 查询详情
  async queryById(id) {
    const statement = `
      SELECT 
        m.id id, m.content content, m.createAt createTime, m.updateAt updateTime,
        JSON_OBJECT('id', u.id, 'name', u.name, 'createTime', u.createAt, 'updateTime', u.updateAt) user
      FROM moment m
      LEFT JOIN user u ON u.id = m.user_id
      WHERE m.id = ?;
    `
    const [result] = await connection.execute(statement, [id])
    console.log(result);
    return result
  }

  // 修改文章
  async update(content,id)
  {
   const statement='UPDATE moment  SET content=? WHERE id=?'
   const [result]=await connection.execute(statement,[content,id])
  return result
  }


  // 删除文章
  async remove(id) {
    const statement = 'DELETE FROM moment WHERE id = ?;';
    const [result] = await connection.execute(statement, [id])

    return result
  }


 }
module.exports = new MomentService();
